cmake_minimum_required(VERSION 3.15)
if(NOT DEFINED SDCC_PATH)
    find_program(SDCC_EXECUTABLE sdcc)
    if(SDCC_EXECUTABLE)
        get_filename_component(SDCC_BIN_DIR "${SDCC_EXECUTABLE}" DIRECTORY)
        if(WIN32)
            get_filename_component(SDCC_ROOT "${SDCC_BIN_DIR}/.." ABSOLUTE)
            set(SDCC_PATH "${SDCC_ROOT}/bin")
            set(SDCC_INCLUDE_PATH "${SDCC_ROOT}/include")
        else()
            set(SDCC_PATH "${SDCC_BIN_DIR}")
            if(APPLE)
                set(SDCC_INCLUDE_PATH "/usr/local/share/sdcc/include")
            else()
                set(SDCC_INCLUDE_PATH "/usr/share/sdcc/include")
            endif()
        endif()
    else()
        message(FATAL_ERROR "SDCC not found. Please install SDCC or set -DSDCC_PATH manually.")
    endif()
else()
    if(NOT IS_ABSOLUTE "${SDCC_PATH}")
        set(SDCC_PATH "${CMAKE_SOURCE_DIR}/${SDCC_PATH}")
    endif()
    if(NOT DEFINED SDCC_INCLUDE_PATH)
        if(WIN32)
            set(SDCC_INCLUDE_PATH "${SDCC_PATH}/../include")
        elseif(APPLE)
            set(SDCC_INCLUDE_PATH "/usr/local/share/sdcc/include")
        else()
            set(SDCC_INCLUDE_PATH "/usr/share/sdcc/include")
        endif()
    endif()
endif()

file(TO_CMAKE_PATH "${SDCC_PATH}" SDCC_PATH)
file(TO_CMAKE_PATH "${SDCC_INCLUDE_PATH}" SDCC_INCLUDE_PATH)

if(NOT EXISTS "${SDCC_PATH}/sdcc" AND NOT EXISTS "${SDCC_PATH}/sdcc.exe")
    message(FATAL_ERROR "SDCC executable not found at ${SDCC_PATH}")
endif()

message(STATUS "Using SDCC from: ${SDCC_PATH}")
message(STATUS "Using SDCC include: ${SDCC_INCLUDE_PATH}")

#默认设置
set(SDCC_PORT mcs51)
set(SDCC_MCS51_MODEL small)
set(SDCC_MCS51_STD sdcc11)
set(SDCC_MCS51_IRAM_SIZE 128)
set(SDCC_MCS51_XRAM_SIZE 0)
set(SDCC_MCS51_CODE_SIZE 4096)
list(APPEND SDCC_MCS51_INCLUDE ${SDCC_INCLUDE_PATH})


macro(add_mcs51_executable MAIN_SOURCE)
get_filename_component(EXECUABLE_NAME ${MAIN_SOURCE} NAME_WE)
set(SDCC_MCS51_EXECUTABLE_SDCC_FLAGS -m${SDCC_PORT} --std-${SDCC_MCS51_STD} --model-${SDCC_MCS51_MODEL} --iram-size ${SDCC_MCS51_IRAM_SIZE} --xram-size ${SDCC_MCS51_XRAM_SIZE} --code-size ${SDCC_MCS51_CODE_SIZE})
foreach(INCLUDE_DIR ${SDCC_MCS51_INCLUDE})
set(SDCC_MCS51_EXECUTABLE_SDCC_FLAGS ${SDCC_MCS51_EXECUTABLE_SDCC_FLAGS} -I ${INCLUDE_DIR})
endforeach()
add_custom_target(${EXECUABLE_NAME}.ihx ALL
                  COMMAND ${SDCC_PATH}/sdcc ${SDCC_MCS51_EXECUTABLE_SDCC_FLAGS} -o ${CMAKE_BINARY_DIR}/${EXECUABLE_NAME}.ihx ${MAIN_SOURCE} ${ARGN}
                  SOURCES ${MAIN_SOURCE}
                  WORKING_DIRECTORY ${CMAKE_BINARY_DIR})
endmacro()

macro(mcs51_include_directories)
list(APPEND SDCC_MCS51_INCLUDE ${ARGN})
endmacro()


